import 'dart:developer';

import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:permission_handler/permission_handler.dart'
    as permission_handler;

import '../index.dart';

/*地图选择*/
class MapSelectPage extends StatefulWidget {
  MapSelectPage({Key? key}) : super(key: key);

  @override
  _MapSelectState createState() => _MapSelectState();
}

class _MapSelectState extends State<MapSelectPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void reassemble() {
    super.reassemble();
  }

  final option = MyLocationOption(
    show: true,
    // 是否显示
    myLocationType: MyLocationType.Show,
  );

  AmapController? _mapController;
  ReGeocode? reGeocode;
  LatLng? coordinate;
  late bool loading = false;

  Future<void> _onMapMoveEnd(MapMove move) async {
    //加载数据当前位置
    if (move.coordinate != null) {
      if (mounted) {
        setState(() {
          loading = true;
        });
      }
      ReGeocode reGeocode = await AmapSearch.instance.searchReGeocode(
        move.coordinate!,
        radius: 200.0,
      );
      Debug.info(reGeocode.toString());
      coordinate = move.coordinate;
      if (mounted) {
        setState(() {
          loading = false;
          this.reGeocode = reGeocode;
        });
      }
    }
  }

  Future<void> _onMapCreated(AmapController controller) async {
    _mapController = controller;
    PermissionHelper.check([permission_handler.Permission.location],
        onSuccess: () async {
      try {
        showToast("定位中...");
        await _mapController?.showMyLocation(option);
        // 延时1s执行返回
        Future.delayed(Duration(seconds: 1), () async {
          LatLng? latLng = await _mapController
              ?.getLocation()
              .whenComplete(() {})
              .timeout(Duration(seconds: 30));
          // Navigator.of(context).pop();
          //移动到当前位置
          if (latLng != null) {
            // debugger(when: true);
            _mapController?.setCenterCoordinate(latLng);
          } else {
            showToast("定位失败");
          }
        });
      } on Error catch (e) {
        // Navigator.of(context).pop();
        showToast("定位失败");
      }
    });

    // if (await permission_handler.Permission.location.request().then((t) => t.isGranted)) {
    //   try {
    //     showToast("定位中...");
    //     await _mapController?.showMyLocation(option);
    //     // 延时1s执行返回
    //     Future.delayed(Duration(seconds: 1), () async {
    //       LatLng? latLng = await _mapController
    //           ?.getLocation()
    //           .whenComplete(() {})
    //           .timeout(Duration(seconds: 30));
    //       // Navigator.of(context).pop();
    //       //移动到当前位置
    //       if (latLng != null) {
    //         _mapController?.setCenterCoordinate(latLng);
    //       } else {
    //         showToast("定位失败");
    //       }
    //     });
    //   } on Error catch (e) {
    //     // Navigator.of(context).pop();
    //     showToast("定位失败");
    //   }
    // } else {
    //   showToast('权限请求被拒绝!');
    // }
  }

  @override
  Widget build(BuildContext context) {
    var darkModel = Provider.of<DarkModel>(context);
    if (_mapController != null) {
      _mapController?.setMapType(
          darkModel.isDark(context) ? MapType.Night : MapType.Standard);
    }

    // context.read<DarkModel>().darModeChange();
    // Brightness brightness = MediaQuery.platformBrightnessOf(context);
    // final AMapWidget map = AMapWidget(
    //   apiKey: ConstConfig.amapApiKeys,
    //   myLocationStyleOptions: MyLocationStyleOptions(
    //     true,
    //     circleFillColor: Colors.lightBlue,
    //     circleStrokeColor: Colors.blue,
    //     circleStrokeWidth: 1,
    //   ),
    //   onMapCreated: _onMapCreated,
    //   onLocationChanged: _onLocationChanged,
    //   onCameraMove: _onCameraMove,
    //   onCameraMoveEnd: _onCameraMoveEnd,
    // );
    String address = "加载中...";
    if (loading) {
      address = "加载中...";
    } else {
      if (reGeocode != null) {
        address = reGeocode!.formatAddress ?? "未知地点";
      } else {
        address = "未知地点";
      }
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text("选择地址"),
        centerTitle: true,
      ),
      body: Stack(
        alignment: Alignment.center, //指定未定位或部分定位widget的对齐方式
        children: <Widget>[
          AmapView(
            mapType:
                darkModel.isDark(context) ? MapType.Night : MapType.Standard,
            onMapCreated: _onMapCreated,
            onMapMoveEnd: _onMapMoveEnd,
            zoomLevel: 15,
          ),
          SizedBox(
            width: 30,
            height: 60,
            child: Align(
              alignment: Alignment.topCenter,
              child: Icon(
                Icons.location_on,
                color: Theme.of(context).primaryColor,
                size: 30,
              ),
            ),
          ),
          Positioned(
            bottom: 20.0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  Expanded(
                      child: Text(address,
                          style: TextStyle(
                              color:
                                  Theme.of(context).colorScheme.onBackground))),
                  ElevatedButton(
                    child: Text(
                      "确定",
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () {
                      //返回上一页 并带入内容
                      if (reGeocode == null) {
                        showToast("未知地址");
                      } else {
                        Navigator.pop(context, [reGeocode, coordinate]);
                      }
                    },
                  )
                ],
              ),
              color: Colors.white54,
            ),
          )
        ],
      ),
    );
  }
}
